package softWareConstructPro;//coding with utf-8

import java.util.ArrayList;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;//not java.sql.Date
import java.text.SimpleDateFormat;

public class Gui extends JFrame implements ActionListener{
	
	private static final long serialVersionUID = 1094660232643596689L;//I do not know what is this
	private ArrayList<JTextField> list = new ArrayList<>();//JTextField的变长数组
	private JPanel jpMain = new JPanel();//用来储存主界面cneter部分组件的JPanel
	private JScrollPane jsp = new JScrollPane(jpMain);//使jpMain这个JPanel组件具有滚动条功能
	private Exercise myex = null;//Exercise类的引用
	private ExerciseSaver exSaver = null;//练习题储存类
	private JMenuBar jmb = null;//菜单条,用来储存各个主菜单选项
	private JMenu jmFile = null, jmOpt = null, jm2_1 = null, jm2_2 = null, jm2_3 = null, jmOpen = null, jmDel = null, jmEx = null;//各个菜单组件(含有子项)
	private	JMenuItem jmSub = null, jmGene = null, jmSave = null, jmReturn = null, jmAttri = null;//各个菜单选项(无子项)
	public Gui() {//默认构造函数
		this.setBounds(350, 350, 410, 280);//设置JFrame组件的基本属性
		this.setResizable(false);
		this.setTitle("Exerciser beta 0.6");
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setLayout(new BorderLayout());
		
		jmAttri = new JMenuItem("");
		jmAttri.setEnabled(false);
		jsp.getVerticalScrollBar();
		jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		jmb = new JMenuBar();
		jmFile = new JMenu("文件");//文件选项
		jmOpen = new JMenu("打开练习");//打开练习题文件选项
		jmDel = new JMenu("删除练习");//删除练习题文件选项
		
		jmFile.add(jmOpen);
		//read file list(open and del)
		jmFile.add(jmDel);
		jmSave = new JMenuItem("保存练习");//保存练习题文件选项
		jmSave.setEnabled(false);
		jmSave.addActionListener(this);
		jmSave.setActionCommand("3,/");//#JOptionPane
		jmFile.add(jmSave);
		//Option
		jmOpt = new JMenu("选项");//"选项"选项
		
		jm2_1 = new JMenu("数量设置");//练习题数量选项
		JMenuItem jmn2_1 = new JMenuItem("20");
		jmn2_1.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				myex.setCapacity(20);
				JOptionPane.showMessageDialog(null, "练习题设置为20道");
				writeExerciseAttri();
			}
		});
		JMenuItem jmn2_2 = new JMenuItem("40");
		jmn2_2.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null, "练习题设置为40道");
				myex.setCapacity(40);
				writeExerciseAttri();
			}
		});
		JMenuItem jmn2_3 = new JMenuItem("50");
		jmn2_3.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null, "练习题设置为50道");
				myex.setCapacity(50);
				writeExerciseAttri();
			}
		});
		JMenuItem jmn2_4 = new JMenuItem("60");
		jmn2_4.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null, "练习题设置为60道");
				myex.setCapacity(60);
				writeExerciseAttri();
			}
		});
		JMenuItem jmn2_5 = new JMenuItem("80");
		jmn2_5.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null, "练习题设置为80道");
				myex.setCapacity(80);
				writeExerciseAttri();
			}
		});
		JMenuItem jmn2_6 = new JMenuItem("100");
		jmn2_6.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null, "练习题设置为100道");
				myex.setCapacity(100);
				writeExerciseAttri();
			}
		});
		JMenuItem jmn2_7 = new JMenuItem("200");
		jmn2_7.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null, "练习题设置为200道");
				myex.setCapacity(200);
				writeExerciseAttri();
			}
		});
		jm2_1.add(jmn2_1);
		jm2_1.add(jmn2_2);
		jm2_1.add(jmn2_3);
		jm2_1.add(jmn2_4);
		jm2_1.add(jmn2_5);
		jm2_1.add(jmn2_6);
		jm2_1.add(jmn2_7);
		jm2_2 = new JMenu("类型选项");//练习题类型选项
		JMenuItem jmt2_0 = new JMenuItem("混合");
		jmt2_0.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				myex.setOp(0);
				JOptionPane.showMessageDialog(null, "练习类型设置为 + 和 -");
				writeExerciseAttri();
			}
		});
		JMenuItem jmt2_1 = new JMenuItem("全 +");
		jmt2_1.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				myex.setOp(1);
				JOptionPane.showMessageDialog(null, "练习类型设置为 +");
				writeExerciseAttri();
			}
		});
		JMenuItem jmt2_2 = new JMenuItem("全 -");
		jmt2_2.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				myex.setOp(-1);
				JOptionPane.showMessageDialog(null, "练习类型设置为 -");
				writeExerciseAttri();
			}
		});
		jm2_2.add(jmt2_0);
		jm2_2.add(jmt2_1);
		jm2_2.add(jmt2_2);
		
		jm2_3 = new JMenu("最大值设置");//练习题最大值选项
		JMenuItem jmKey1 = new JMenuItem("100");
		jmKey1.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				myex.setMaxKey(100);
				JOptionPane.showMessageDialog(null, "最大值设置为100");
				writeExerciseAttri();
			}
		});
		JMenuItem jmKey2 = new JMenuItem("1000");
		jmKey2.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				myex.setMaxKey(1000);
				JOptionPane.showMessageDialog(null, "最大值设置为1000");
				writeExerciseAttri();
			}
		});
		jm2_3.add(jmKey1);
		jm2_3.add(jmKey2);
		
		
		jmOpt.add(jm2_1);
		jmOpt.add(jm2_2);
		jmOpt.add(jm2_3);
		//Exercise Option
		jmEx = new JMenu("开始");
		jmSub = new JMenuItem("提交");//提交选项
		jmSub.setEnabled(false);
		jmSub.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				exerciseCorrecting();
				//
				int ans = JOptionPane.showConfirmDialog(null, "保存练习?\n", "选择是否保存练习", JOptionPane.YES_NO_OPTION);
				if(ans == 1) {
					JOptionPane.showMessageDialog(null, "练习未保存");
				}
				else {// problem
					saveFileFunc("");
					
				}
				//
				ans = JOptionPane.showConfirmDialog(null, "停止做题并退出?\n", "退出", JOptionPane.YES_NO_OPTION);
				if(ans != 1) {
					enableFunc();
					startScreen();
					repaint();
				}
			}
		});
		jmGene = new JMenuItem("生成练习");//生成练习题选项
		jmGene.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				myex.regenerateExercise();
				clearScreen();
				init();//and set jm.Enable(false)!
				disableFunc();
				repaint();//#
			}
		});
		jmReturn = new JMenuItem("返回");//返回选项
		jmReturn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(myex.ifUsing() == true) {
					int ans = JOptionPane.showConfirmDialog(null, "停止做题并退出?\n", "退出", JOptionPane.YES_NO_OPTION);
					if(ans == 1) {
						JOptionPane.showMessageDialog(null, "您取消了退出");
					}
					else {
						enableFunc();
						startScreen();
						repaint();
					}
				}
			}
		});
		jmEx.add(jmGene);
		jmEx.add(jmSub);
		jmEx.add(jmReturn);
		jmb.add(jmFile);
		jmb.add(jmOpt);
		jmb.add(jmEx);
		jmb.add(jmAttri);
		
		this.writeExerciseAttri();
		this.add(jmb,"North");
		this.startScreen();//#
		this.setVisible(true);
	}
	private void disableFunc() {//开启,闲置时主界面各组件的属性
		myex.setUsing();
		jmSave.setEnabled(true);
		jmOpen.setEnabled(false);
		jmDel.setEnabled(false);
		jm2_1.setEnabled(false);
		jm2_2.setEnabled(false);
		jm2_3.setEnabled(false);
		jmGene.setEnabled(false);
		jmSub.setEnabled(true);
	}
	private void enableFunc() {//做练习题时主界面各组件的属性
		myex.afterUsed();//清除Exercise类中BinaryOperation动态数组的所有元素
		jmSave.setEnabled(false);
		jmOpen.setEnabled(true);
		jmDel.setEnabled(true);
		jm2_1.setEnabled(true);
		jm2_2.setEnabled(true);
		jm2_3.setEnabled(true);
		jmGene.setEnabled(true);
		jmSub.setEnabled(false);
	}
	private void exerciseCorrecting() {//练习题打分函数
		int correct = 0;//试题做对数量
		int len = list.size();
		for(int i = 0; i < len; ++i) {
			JTextField ansJ = this.list.get(i);
			String result = this.myex.getBO(i).getResult() + "";
			if(result.equals(ansJ.getText())) {
				correct++;
				ansJ.setBackground(Color.GREEN);//对的答案标绿色
			}
			else {
				ansJ.setBackground(Color.RED);//错的答案标红色
			}
		}
		JOptionPane.showMessageDialog(null, "您做对了 " + correct + " 道题\n 全部题数: " + len);
	}
	public void getExercise(Exercise myext) {//得到外界的Exercise的引用,并且创建一个自己的练习题存储类的实体exSaver
		this.myex = myext;
		this.exSaver = new ExerciseSaver(this.myex, this.list);
		this.loadExName();//need to correct how to use
	}
	public void init(){//初始化练习题并显示出来
		this.writeExerciseAttri();
		int capacity = this.myex.getCapacity();
		if(myex.ifUsing() == false)
			this.myex.setUsing();//remember to setUsing
		jpMain.setLayout(new GridLayout(capacity/2,2));//设置jpMain的格式为n * 2
		BinaryOperation bot = null;
		boolean flag = true;
		if(list.size() > 0) {
			flag = false;
		}
		for(int i = 0; i < capacity; ++i){//循环加载组件
			bot = this.myex.getBO(i);
			JPanel jp = new JPanel();
			//System.out.println((""+bot).length());
			JLabel jLabel = new JLabel(""+bot);
			if(flag) {
				JTextField jTextField = new JTextField(5);
				jTextField.setEditable(true);
				list.add(jTextField);
			}
			jp.add(jLabel);
			jp.add(this.list.get(i));
			jpMain.add(jp);
		}
		this.add(jsp,"Center");//设置jpMain组件在JFrame的中央
		this.setVisible(true);
	}
	public void startScreen() {//在开启,空闲时的JFrame的center部分显示图片
		//add a picture to start Screen
		clearScreen();
		//String path = "src/start.jpg";
		java.net.URL imgURL = this.getClass().getResource("/start.JPG");
		Icon icon = new ImageIcon(imgURL);
		JLabel jlpic = new JLabel();
		jlpic.setSize(400, 300);
		jlpic.setIcon(icon);
		this.jpMain.add(jlpic);
		this.add(jsp,"Center");
		this.repaint();
	}
	public void clearScreen() {//清除界面中的练习题函数,深层则清除JTextField动态数组中的元素,使动态数组list为空,防止其非空引起下一次读入试题时的试题数量不正确
		this.jpMain.removeAll();
		this.list.clear();
		this.repaint();
	}
	public void print(){//打印用户的作答到控制台上,查看作答情况
		int len = list.size();
		for(int i = 0; i < len; ++i){
			System.out.println(list.get(i).getText());
		}
	}
	private void loadExName() {//加载所有练习题文件的函数(向打开,删除菜单中加载)
		this.jmOpen.removeAll();
		this.jmDel.removeAll();
		this.repaint();
		exSaver.readAllFileName();
		int len = exSaver.fileList.size();
		//System.out.println(len);
		if(len == 0) {
			JMenuItem jmi1 = new JMenuItem("空空如也");
			JMenuItem jmi2 = new JMenuItem("空空如也");
			jmOpen.add(jmi1);
			jmDel.add(jmi2);
		}
		else {//参考网址
			//https://zhidao.baidu.com/question/184985257.html?qbl=relate_question_0&word=Java%20jmenuitem%B5%C4%B1%EA%C7%A9
			for(int i = 0; i < len; ++i) {
				JMenuItem jmi1 = new JMenuItem(exSaver.fileList.get(i));
				jmi1.addActionListener(this);
				jmi1.setActionCommand("0," + exSaver.fileList.get(i));
				JMenuItem jmi2 = new JMenuItem(exSaver.fileList.get(i));
				jmi2.addActionListener(this);
				jmi2.setActionCommand("1," + exSaver.fileList.get(i));
				jmOpen.add(jmi1);
				jmDel.add(jmi2);
			}
		}
	}
	private void saveFileFunc(String fileName) {//存储练习题到文件中的函数,独立成一个函数防止多次重写同样代码段
		String str = null;
		boolean check = false;
		do {
			fileName = "";
			check = false;
			str = JOptionPane.showInputDialog(null, "请输入文件名:\n 您可以用大小写字母, 数字, 和空格, 下划线 来对您的文件命名 \n 什么也不输入直接点击确定会根据时间生成文件名", "保存文件", JOptionPane.CANCEL_OPTION);
			//System.out.println(str);
			if(str == null) {
				JOptionPane.showMessageDialog(null, "您取消了文件的保存!\\n 文件不会被保存下来."," ", JOptionPane.YES_OPTION);
				//System.out.println("you canceled the save function!\n so the file do not saved.");
				check = false;
			}
			else if(str.equals("")) {
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHss");//利用时间类产生当前时间的年月日时秒字符串,保证文件名不重复
				str = dateFormat.format(new Date());
			}
			else {
				for(int i = 0; i < str.length(); ++i) {
					char ch = str.charAt(i); 
					if(ch == ' ' || ch == '_' ||(ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
						continue;
					}
					else {
						check = true;
						break;
					}
				}
			}
			if(str != null && check == false) {
				fileName += str;
				fileName += ".txt";
				//System.out.println(fileName);//$
				if(exSaver.createExerciseFile(fileName) == true) {
					JOptionPane.showMessageDialog(null, fileName + "创建成功!");
					check = false;
					break;
				}
				else {
					JOptionPane.showMessageDialog(null, fileName + "创建失败!\n 可能的原因： 文件已经存在!");
					check = true;
				}
				
			}
		}while(check == true);
		//System.out.println(str);
		
	}
	public void actionPerformed(ActionEvent e) {//当菜单选项被按下时
		String fileName = "";
		if(e.getActionCommand().charAt(0) == '0') {//字符串开头为0时表示打开文件操作
			fileName = e.getActionCommand().split(",")[1];
			exSaver.loadExercise(fileName);
			this.loadExName();
			this.clearScreen();
			this.init();
			disableFunc();
			repaint();
		}
		else if(e.getActionCommand().charAt(0) == '1'){//1表示删除文件操作
			fileName = e.getActionCommand().split(",")[1];
			int op = JOptionPane.showConfirmDialog(null, "你想删除练习题文件 " + fileName + "吗?\n", "确认您的操作", JOptionPane.YES_NO_OPTION);
			if(op == 1) {
				JOptionPane.showMessageDialog(null, "你取消了删除文件");
			}
			else {
				if(exSaver.deleteExerciseFile(fileName) == true) {
					JOptionPane.showMessageDialog(null, fileName + "删除成功!");
				}
				else {
					JOptionPane.showMessageDialog(null, "删除失败!\n " + fileName + " 不存在!");
				}
				
				this.loadExName();
			}
			
		}
		else if(e.getActionCommand().charAt(0) == '3') {//3表示新建练习题文件函数
			this.saveFileFunc(fileName);
		}
		this.loadExName();
	}
	private void writeExerciseAttri() {
		String text = "";
		if(myex == null) {
			text += "最大值: -- 类型: -- 数量: --";
		}
		else {
			text += "最大值: " + myex.getMaxKey() + " 类型: ";
			if(myex.getOp() == 0) {
				text += "+ 和 - 数量: ";
			}else if(myex.getOp() == 1) {
				text += "+ 数量: ";
			}else {
				text +="- 数量: ";
			}
			text += myex.getCapacity();
		}
		this.jmAttri.setText(text);
	}
	/*
	public static void main(String[] argv){
		Exercise myex = new Exercise();
		Gui myGui = new Gui();
		myGui.getExercise(myex);
		
	}*/
}
